/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bd1.obli2012.gui;

import bd1.obli2012.framework.ColumnManager;
import bd1.obli2012.framework.definicion.Columna;
import bd1.obli2012.framework.DatabaseManager;
import bd1.obli2012.framework.ExecutionResult;
import bd1.obli2012.framework.TablaManager;
import bd1.obli2012.framework.definicion.Tabla;
import bd1.obli2012.gui.backend.Contexto;
import bd1.obli2012.versionado.Cambio;
import bd1.obli2012.versionado.TipoCambio;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author favio.ortelli/guillermo.nasi
 */
public class PanelTabla extends javax.swing.JPanel {

    private DefaultTableModel tableModel;
    private String dbName;
    private String tbName;
    private String tempTbName;
    private MainFrame parent;
    private boolean lock = false;
    private TablaManager tm = new TablaManager();

    /**
     * Creates new form TablePanel
     */
    public PanelTabla(String dbName, String tbName, MainFrame parent) {
        this.dbName = dbName;
        this.tbName = tbName;
        this.parent = parent;
        initComponents();
        cargarInformacionTabla();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tablaAtributos = new javax.swing.JTable();
        btnAgregarAttr = new javax.swing.JButton();
        btnEditarAttr = new javax.swing.JButton();
        btnQuitarAttr1 = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(800, 400));
        setPreferredSize(new java.awt.Dimension(800, 400));

        tablaAtributos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Tipo dato", "Valor por Defecto", "Not Null", "Primary Key", "Foreign Key", "Reference"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tablaAtributos);

        btnAgregarAttr.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bd1/obli2012/icons/buttons/add.png"))); // NOI18N
        btnAgregarAttr.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarAttrActionPerformed(evt);
            }
        });

        btnEditarAttr.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bd1/obli2012/icons/buttons/edit.png"))); // NOI18N
        btnEditarAttr.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarAttrActionPerformed(evt);
            }
        });

        btnQuitarAttr1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bd1/obli2012/icons/buttons/delete.png"))); // NOI18N
        btnQuitarAttr1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitarAttr1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 720, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(btnQuitarAttr1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnEditarAttr, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnAgregarAttr, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 37, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnAgregarAttr, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEditarAttr, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnQuitarAttr1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarAttrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarAttrActionPerformed
        DialogAddAttrib j = new DialogAddAttrib(null, true, dbName, tbName, this);
        j.setVisible(true);
    }//GEN-LAST:event_btnAgregarAttrActionPerformed

    private void btnEditarAttrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarAttrActionPerformed
        DialogModAttrib j = new DialogModAttrib(null, true, dbName, tbName, getSelectedColumnName(), this);
        j.setVisible(true);
    }//GEN-LAST:event_btnEditarAttrActionPerformed

    private void btnQuitarAttr1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitarAttr1ActionPerformed

        
        //Preparamos el cambio en caso de que se borre correctamente la columna
        String colName = getSelectedColumnName();
        Columna columna = DatabaseManager.getInstance().getColumnFromTable(dbName, tbName, colName);
        Map<String, String> parametros = new HashMap<String, String>();
        parametros.put("NOMBRE_TABLA", tbName);
        parametros.put("NOMBRE_COLUMNA", colName);
        parametros.put("TIPO", columna.getTipo().toString());
        parametros.put("NOT_NULL", columna.notNull().toString());
        Cambio cambio = new Cambio(TipoCambio.COLUMNA_BORRAR, parametros);
        


        ColumnManager columnManager = new ColumnManager();
        ExecutionResult er = columnManager.dropColumn(dbName, tbName, colName);
        if (er.success) {
            Contexto.getInstance().guardarCambio(cambio);
        } else {
            JOptionPane.showMessageDialog(parent, er.errorMessage, "Error", JOptionPane.ERROR_MESSAGE);
        }


        actualizarDatos();
    }//GEN-LAST:event_btnQuitarAttr1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarAttr;
    private javax.swing.JButton btnEditarAttr;
    private javax.swing.JButton btnQuitarAttr1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tablaAtributos;
    // End of variables declaration//GEN-END:variables

    /**
     * Carga los datos de la tabla seleccionada en el panel
     *
     * @param tabla
     */
    private void cargarInformacionTabla() {
        DefaultTableModel model = (DefaultTableModel) tablaAtributos.getModel();

        //vaciar tabla
        while (model.getRowCount() > 0) {
            model.removeRow(0);
        }
        /*
         tableModel.addColumn("Nombre");
         tableModel.addColumn("Tipo dato");
         tableModel.addColumn("Valor por Defecto");
         tableModel.addColumn("Nulo?");
         tableModel.addColumn("Primary Key");
         tableModel.addColumn("Foreign Key");
         tableModel.addColumn("Reference");
         */
        Tabla tabla = DatabaseManager.getInstance().getTable(dbName, tbName);
        for (Columna a : tabla.getAttributes()) {
            model.addRow(
                    new Object[]{
                        a.getNombre(),
                        a.getTipo(),
                        a.getDefaultValue(),
                        !a.isNullable(),
                        tabla.isPrimaryKey(a.getNombre()),
                        tabla.isForeignKey(a.getNombre()),
                        tabla.reference(a.getNombre())
                    });
        }

    }

    public void actualizarDatos() {
        cargarInformacionTabla();
        //FIXME
        this.parent.cargarArbol();
    }

    /**
     * Obtiene el nombre del atributo seleccionado de la tabla
     *
     * @return
     */
    private String getSelectedColumnName() {
        Integer row = tablaAtributos.getSelectedRow();
        return tablaAtributos.getValueAt(row, 0).toString();
    }
}
